import axios from "axios";

import { NewsSummary } from "@/entity/NewsSummary";

const API_URL = "http://localhost:8080";

export const fetchAllIds = async (): Promise<string[]> => {
  return axios
    .get(API_URL + "/news")
    .then((response) => {
      return response.data;
    })
    .catch((error) => {
      throw new Error(error);
    });
};

export const fetchNewsSummary = async (): Promise<NewsSummary[]> => {
  const ids = await fetchAllIds();
  // console.log(ids);
  return await Promise.all(
    ids.map(async (id) => {
      try {
        const response = await axios.get(API_URL + "/news/summary?id=" + id);
        return new NewsSummary(id, response.data.title, response.data.summary);
      } catch (error) {
        throw new Error(error as string);
      }
    })
  );
};

export const fetchNewsContent = async (id: string): Promise<string> => {
  return axios
    .get(API_URL + "/news/content?id=" + id)
    .then((response) => {
      return response.data;
    })
    .catch((error) => {
      throw new Error(error);
    });
};
